<template>
    <rx-layout>
        <div slot="center">
            <a-form-model ref="form" :model="extJson" :rules="rules">
                <a-tabs v-model="activeKey" class="tabBox">
                    <a-tab-pane :tab="i18n('form.viewConfiguration','视图配置')" key="columnConf" :closable="false">
                        <a-row>
                            <a-col :span="7">
                                <a-form-model-item :label="i18n('form.primaryKey','主键字段')" prop="idField">
                                    <a-select style="width: calc(100% - 50px)" v-model="extJson.columnConf.idField"
                                              allowClear :options="fieldColumns"></a-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="3">
                                <a-form-model-item :label="i18n('form.timeSlot','时间段')">
                                    <a-switch v-model="extJson.columnConf.timeQuantum" @change="timeQuantumChange"/>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <div class="refererEdit-center-header">
                                <div><span @click="addTimeField" style="cursor: pointer"><my-icon
                                    type="iconxinzeng"></my-icon><span>
                                    {{i18n('form.AddFields','新增一组日期字段')}}
                                </span></span></div>
                            </div>
                            <div style="margin-top: 17px">
                                <div class="refererEdit-common"
                                     v-for="(timeField,index) in extJson.columnConf.timeFields" :key="index">
                                    <div>
                                        <my-icon @click="delTimeField(index)" type="iconoffline"
                                                 style="cursor: pointer"></my-icon>
                                    </div>
                                    <div style="flex: 1">
                                        <a-row>
                                            <a-col :span="7">
                                                <a-form-model-item :label="i18n('form.startTime','开始时间')" prop="timeFields">
                                                    <a-select style="width: calc(100% - 50px)"
                                                              v-model="timeField.startField" allowClear
                                                              :options="fieldColumns"></a-select>
                                                </a-form-model-item>
                                            </a-col>
                                            <a-col :span="7">
                                                <a-form-model-item :label="i18n('form.endTime','结束时间')" v-if="extJson.columnConf.timeQuantum">
                                                    <a-select style="width: calc(100% - 50px)"
                                                              v-model="timeField.endField" allowClear
                                                              :options="fieldColumns"></a-select>
                                                </a-form-model-item>
                                            </a-col>
                                            <a-col :span="7">
                                                <a-form-model-item :label="i18n('form.colorProfile','颜色配置')">
                                                    <div style="display: flex;margin-top: 5px">
                                                        <a-input style="width: 50px" v-model="timeField.background"
                                                                 type="color" :placeholder="i18n('form.bgColor','背景颜色')"/>
                                                        <div v-if="timeField.background"
                                                             :style="{background:hexToRgb(timeField.background).rgb,color:timeField.background,borderLeft:'4px solid'+timeField.background}"
                                                             class="preview-effect">{{i18n('form.previewEffect','预览效果')}}
                                                        </div>
                                                    </div>
                                                </a-form-model-item>
                                            </a-col>
                                        </a-row>
                                    </div>
                                </div>
                            </div>
                        </a-row>
                        <a-collapse v-model="panelActiveKeys" expandIconPosition="right">
                            <a-collapse-panel key="monthColumnConf" :header="i18n('form.monthlyViewConfiguration','月视图配置')" class="cp-box">
                                <div class="monthColumnConf-map">
                                    <div class="monthColumnConf-head"><i class="iconfont iconicon-test33"></i>
                                        {{i18n('form.monthColumnConfHead','Click on the corresponding field values in the dashed box below to piece together the title displayed in the month view. For example, Zhang San applied for a 3-day annual leave') }}
                                    </div>
                                    <div>
                                        <a-form-model-item :label="i18n('form.showMonthView','显示月视图')">
                                            <a-switch v-model="extJson.columnConf.monthConf.show"/>
                                        </a-form-model-item>
                                    </div>
                                </div>
                                <div class="monthColumnConf-content">
                                    <div class="monthColumnConf-content-fileid" v-for="(field,index) in fieldColumns"
                                         :key="index">
                                        <i class="iconfont"
                                           :class="{'iconField-String':field.dataType =='string','iconshuzi':field.dataType =='number','iconriqi':field.dataType =='date'}"></i>{{ field.label }}<span
                                        class="monthColumnConf-content-fileid-span"
                                        @click="selectField(field.value)">{{ field.value }}</span>
                                    </div>
                                </div>
                                <div class="monthColumnConf-content-label">
                                    <span style="line-height: 36px">
                                        {{i18n('form.titleConfiguration','标题配置')}}
                                    </span>
                                    <div class="monthColumnConf-content-label-allocation">
                                        <a-input v-model="extJson.columnConf.monthConf.monthTitle"></a-input>
                                    </div>
                                </div>
                            </a-collapse-panel>
                        </a-collapse>
                        <a-collapse v-model="panelActiveKeys" expandIconPosition="right" style="margin-top: 10px">
                            <a-collapse-panel key="weekColumnConf" :header="i18n('form.weeklyViewConfiguration','周视图配置')" class="cp-box">
                                <a-row>
                                    <a-col :span="2">
                                        <a-form-model-item :label="i18n('form.showWeekView','显示周视图')">
                                            <a-switch v-model="extJson.columnConf.weekConf.show"/>
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                                <a-row>
                                    <FormCalendarViewGrid ref="weekColumns"
                                                          :viewColumns="extJson.columnConf.weekConf.weekColumns"
                                                          :fieldColumns="this.fieldColumns"></FormCalendarViewGrid>
                                </a-row>
                            </a-collapse-panel>
                        </a-collapse>
                        <a-collapse v-model="panelActiveKeys" expandIconPosition="right" style="margin-top: 10px">
                            <a-collapse-panel key="dayColumnConf" :header="i18n('form.dailyViewConfiguration','日视图配置')" class="cp-box">
                                <a-row>
                                    <a-col :span="2">
                                        <a-form-model-item :label="i18n('form.showDayView','显示日视图')">
                                            <a-switch v-model="extJson.columnConf.dayConf.show"/>
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                                <a-row>
                                    <FormCalendarViewGrid ref="dayColumns"
                                                          :viewColumns="extJson.columnConf.dayConf.dayColumns"
                                                          :fieldColumns="this.fieldColumns"></FormCalendarViewGrid>
                                </a-row>
                            </a-collapse-panel>
                        </a-collapse>
                    </a-tab-pane>
                    <a-tab-pane :tab="i18n('form.powerConfiguration','权限配置')" key="permissionConf" :closable="false">
                        <FormCalendarViewPermission ref="permissionConf" :pkId="pkId" :buttonConf="extJson.buttonConf"
                                                    :calendarView="mdl"
                                                    :fieldDatas="fieldColumns"></FormCalendarViewPermission>
                    </a-tab-pane>
                    <a-tab-pane :tab="i18n('form.buttonConfiguration','按钮配置')" key="buttonConf" :closable="false">
                        <div class="table-operator">
                            <a-button @click="addBtn">
                                {{i18n('isButton.addButton','新增按钮')}}
                            </a-button>
                            <a-button @click="setDefBtns">
                                {{i18n('isButton.addAllDefaults','新增全部默认')}}
                            </a-button>
                            <a-button @click="removeBtn">
                                {{i18n('isButton.deleteButton','删除按钮')}}
                            </a-button>
                            <a-button @click="upBtn">
                                {{i18n('isButton.upward','向上')}}
                            </a-button>
                            <a-button @click="downBtn">
                                {{i18n('isButton.downward','向下')}}
                            </a-button>
                            <a-button  @click="moveTopUp">{{ i18n_('list.topUp', '置顶') }}</a-button>
                            <a-button  @click="bottomUp">{{ i18n_('list.bottomUp', '置底') }}</a-button>
                            <a-button @click="joinToolbarRs">
                                {{i18n('isButton.joinPermissionResources','加入权限资源')}}
                            </a-button>
                        </div>
                        <rx-grid
                            style="min-height: 600px;"
                            ref="table_Btn"
                            :dataSource="extJson.buttonConf"
                            :columns="btnColumns"
                            :allowRowSelect="true"
                            :multiSelect="true"
                            :showPage="false"
                            :bordered="true"
                            id-field="idx_"
                        >
                            <span slot="btnLabel" slot-scope="{text,record,index}">
                                <a-input v-model="record.btnLabel"/>
                            </span>
                            <span slot="btnName" slot-scope="{text,record,index}">
                                <template v-if="record.isDefault">
                                  {{ record.btnName }}
                                 </template>
                                <template v-else>
                                    <a-input v-model="record.btnName"/>
                                </template>
                            </span>
                            <span slot="btnClick" slot-scope="{text,record,index}">
                              <template v-if="record.isDefault">
                                  {{ record.btnClick }}
                              </template>
                              <template v-else>
                                <a-input v-model="record.btnClick"/>
                              </template>
                          </span>
                            <span slot="btnType" slot-scope="{text,record,index}">
                               <a-radio-group :disabled="record.isDefault" v-model="record.btnType">
                                    <a-radio value="row">
                                         {{i18n('isButtonSizeMap.row','行内')}}
                                    </a-radio>
                                    <a-radio value="head">
                                         {{i18n('isButtonSizeMap.head','头部')}}
                                    </a-radio>
                                </a-radio-group>
                            </span>
                        </rx-grid>
                    </a-tab-pane>
                    <a-tab-pane :tab="i18n('form.jsScript','js脚本')" key="jsScript" :closable="false">
                        <div style="height: 100%;overflow: hidden">
                            <rx-monaco-editor
                                ref="mobileScript"
                                v-model="extJson.jsScript"
                                language="javascript"
                                style="height: 600px "
                            >
                            </rx-monaco-editor>
                        </div>
                    </a-tab-pane>
                </a-tabs>
            </a-form-model>
        </div>
    </rx-layout>
</template>
<script>

import FormCalendarViewEdit2 from './js/FormCalendarViewEdit2'
import FormCalendarViewGrid from './FormCalendarViewGrid'
import FormCalendarViewShow from './FormCalendarViewShow'
import {RxDialog, RxMonacoEditor, BaseFormModel, Util} from "@lowcode/jpaas-common-lib";
import FormCalendarViewPermission from "@/views/modules/form/core/FormCalendarViewPermission";
import SysAppApi from "@/api/system/core/sysApp";
import {openUrl} from "@/utils/util";

export default {
    name: 'FormCalendarViewEdit2',
    mixins: [FormCalendarViewEdit2, BaseFormModel],
    data() {
        let checkIdField = (rule, value, callback) => {
            if (!this.extJson.columnConf.idField) {
                callback(new Error(this.i18n('form.keyRequired','主键字段必填')));
            } else {
                callback();
            }
        };
        return {
            panelActiveKeys: ['monthColumnConf', 'weekColumnConf', 'dayColumnConf'],
            monthTitle: [],
            rules: {
                idField: [{ validator: checkIdField, trigger: 'change',required: true}]
            },
        }
    },
    components: {
        RxDialog,
        FormCalendarViewGrid,
        RxMonacoEditor,
        FormCalendarViewPermission
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"FormCalendarView",key);
        },
        i18n_(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
        moveTopUp(){
            this.$refs.table_Btn.moveTopUp();
        },
        bottomUp(){
            this.$refs.table_Btn.moveBottomUp();
        },
        handleSubmit(self, this_, callback) {
            var extJson = this_.mdl.extJson ? JSON.parse(this_.mdl.extJson) : {};
            extJson = Object.assign(extJson, this_.extJson);
            if (this_.$refs.table_Btn) {
                extJson.buttonConf = this_.$refs.table_Btn.dataAction;
            }
            if (this_.$refs.weekColumns) {
                extJson.columnConf.weekConf.weekColumns = this_.$refs.weekColumns.dataSource;
            }
            if (this_.$refs.dayColumns) {
                extJson.columnConf.dayConf.dayColumns = this_.$refs.dayColumns.dataSource;
            }
            if (!extJson.columnConf.timeFields || extJson.columnConf.timeFields.length == 0) {
                self.$message.warning(self.i18n('form.fieldConfigured','未配置日期字段！'));
                return;
            }else {
                for (let i = 0; i < extJson.columnConf.timeFields.length ; i++) {
                    var timeField=extJson.columnConf.timeFields[i];
                    if(!timeField.startField){
                        self.$message.warning(self.i18n('form.startTimeIsRequired','开始时间必填！'));
                        return;
                    }
                    if(extJson.columnConf.timeQuantum && !timeField.endField){
                        self.$message.warning(self.i18n('form.endTimeIsRequired','结束时间必填！'));
                        return;
                    }
                }
            }
            this_.mdl.extJson = JSON.stringify(extJson);
            this_.$refs.form.validate(valid => {
                if (valid) {
                    this_.save(this_.mdl).then(res => {
                        if (res.success) {
                            if (this_.activeKey == 'permissionConf') {
                                this_.$refs[this_.activeKey].loadData();
                            }
                            let appId = this_.mdl.appId || "";
                            if(!appId){
                                return;
                            }
                            let ctxPath= process.env.VUE_APP_CONTEXT_MAIN;
                            let url=`${ctxPath}/calendarView/${this_.mdl.key}?appId=${appId}`;
                            let title=this_.mdl.name + self.i18n('form.calendarView','日历视图');
                            openUrl({url:url,title:title,curVm:this_,max:true});
                        }
                    })
                }
            });
        },
        timeQuantumChange(value) {
            if (!value) {
                this.extJson.columnConf.endField = "";
            }
        },
        /**
         * HEX十六进制颜色值转换为RGB(A)颜色值
         */
        hexToRgb(val) {
            if (!val || !val.toLowerCase() || val == undefined) {
                return
            }
            //HEX十六进制颜色值转换为RGB(A)颜色值
            // 16进制颜色值的正则
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            // 把颜色值变成小写
            var color = val.toLowerCase();
            var result = '';
            if (reg.test(color)) {
                // 如果只有三位的值，需变成六位，如：#fff => #ffffff
                if (color.length === 4) {
                    var colorNew = "#";
                    for (var i = 1; i < 4; i += 1) {
                        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
                    }
                    color = colorNew;
                }
                // 处理六位的颜色值，转为RGB
                var colorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
                }
                result = "rgb(" + colorChange.join(",") + ",.2" + ")";
                return {rgb: result, r: colorChange[0], g: colorChange[1], b: colorChange[2]};
            } else {
                return {rgb: '-1'};
            }
        }
    },
    watch: {}
}
</script>
<style scoped>
.preview-effect {
    font-size: 13px;
    width: 68px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    border-radius: 4px;
    margin-left: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.refererEdit-common {
    display: flex;
}

.refererEdit-common > div:nth-child(1) {
    margin-top: 9px;
    margin-right: 5px;
}

.monthColumnConf-map {
    display: flex;
}

.monthColumnConf-map > div:nth-child(1) {
    margin-right: 10px;
}

.monthColumnConf-content-fileid-allocation i {
    color: #9babed;
    font-size: 20px;
    line-height: 25px;
    margin-right: 4px;
    float: left;
}

.monthColumnConf-content-label-allocation {
    width: 100%;
    flex: 1;
    overflow: hidden;
    margin-left: 9px;
    margin-top: 2px;
}

.monthColumnConf-content-label {
    display: flex;
    margin-top: 10px;
}

.monthColumnConf-content {
    margin-top: 9px;
    width: 100%;
    overflow: hidden;
    border-radius: 4px;
    padding: 0px 16px 9px 16px;
    border: dashed 1px #dadde0;
}

.monthColumnConf-content i {
    color: #02c5b7;
    font-size: 20px;
    line-height: 21px;
    margin-right: 4px;
    float: left;
}

.monthColumnConf-content-fileid-span {
    height: 26px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: solid 1px #dadde0;
    color: #555555;
    padding: 7px 8px;
    font-size: 12px;
    margin-left: 5px;
    cursor: pointer;
}

.monthColumnConf-content-fileid {
    width: 20%;
    float: left;
    margin-top: 15px;
}

.monthColumnConf-head {
    width: 500px;
    font-family: MicrosoftYaHei;
    font-size: 12px;
    padding: 10px 14px;
    color: #555555;
    border: solid 1px #e6e8eb;
    border-radius: 2px;
    border-left: 4px solid #2e8cff !important;
}

.monthColumnConf-head i {
    color: #2e8cff;
    margin-right: 9px;
}

.cp-box >>> .ant-collapse-content {
    overflow: visible;
}

.relick a {
    margin-right: 10px;
}

.refererEdit-center-header {
    display: flex;
    border-bottom: dashed 1px #dedede;
    height: 40px;
    line-height: 40px;
    font-size: 15px;
}

.refererEdit-center-header i {
    margin-right: 5px;
}
</style>
